<?php
namespace api\modules\v1\models\address;

use common\models\Functions;
use common\models\Patterns;
use common\models\Status;
use yii\base\Exception;
use api\modules\v1\models\user\User;
use Yii;

/**
 * 用户真实收货地址
 * @property int $id
 * @property string $name
 */
class UserAddress extends \common\models\address\UserAddress
{
    /**
     * 验证规则
     */
    public function rules()
    {
        return [
            [['province', 'city','area','detail','name','phone'], 'required','message' => '{attribute}不能为空','on' => 'addEdit'],
            [['phone'],'match','pattern' => Patterns::phoneNumber(),'message' => '手机号码格式不正确','on' => ['addEdit']],
            [['name','phone'], 'filter', 'filter' => 'trim','on' => ['addEdit']],
            [['province','city','area'], 'filter', 'filter' => 'intval','on' => ['addEdit']],
            ['area', 'validateCheckAddress', 'on' => 'addEdit'],

        ];
    }

    /**
     * 设置属性名称
     * @return array
     */
    public function attributeLabels() {
        return [
            'province' => '省',
            'city' => '市',
            'area' => '区',
            'detail' => '详细地址',
            'name' => '联系人',
            'phone' => '联系方式',
        ];
    }

    /**
     * 设置场景
     * @return array
     */
    public function scenarios() {
        $newScenarios =  [
            'addEdit' => [
                'province',
                'city',
                'area',
                'detail',
                'name',
                'phone',
            ],
        ];
        return array_merge(parent::scenarios(), $newScenarios);
    }

    public function validateCheckAddress($attribute) {
        if (!$this->hasErrors()) {
            ConfigAddress::checkAddress($this->province, $this->city, $this->area);
        }
    }
    /**
     * 收货地址列表
     * @return array
     */
    public function getList() {
        try {
            $userInfo = (new User())->checkUser();

            $where['is_delete'] = Status::COMMON_STATUS_SHOW;
            $where['user_id'] = $userInfo['id'];

            $order = 'is_default ASC,create_time DESC';
            $list = static::getByWhere($where,'*',$order);
            $return = [];

            foreach ($list as $v) {
                $PCA = ConfigAddress::getAddress($v['province'], $v['city'], $v['area']);
                $tmp = [
                    "id" => (int) $v['id'],
                    "province" => $v['province'],
                    "city" => $v['city'],
                    "area" => $v['area'],
                    "province_name" => $PCA['province'],
                    "city_name" => $PCA['city'],
                    "area_name" => $PCA['area'],
                    "detail" => $v['detail'],
                    "name" => $v['name'],
                    "phone" => $v['phone'],
                    "is_default" => $v['is_default'] == 1 ? true : false,
                ];

                $return[] = $tmp;
            }

            return Functions::formatRestAPI(0, '', $return);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    /**
     * 添加修改地址
     * @return array
     * @throws \yii\db\Exception
     */
    public function addEdit() {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $user = (new User())->checkUser();
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            $post = \Yii::$app->request->post();
            $id = (int) $post['id'];
            $data['is_default'] = $post['is_default'] == Status::COMMON_RADIO_YES ? Status::COMMON_RADIO_YES : Status::COMMON_RADIO_NO;

            if ($data['is_default'] == Status::COMMON_RADIO_YES) {
                //设置默认的话，将之前的所有设置为非默认
                $removeDefault['is_default'] = Status::COMMON_RADIO_NO;
                $removeDefault['update_time'] = date("Y-m-d H:i:s");
                $res = static::updateData($removeDefault, ['user_id' => $user['id']]);
                if ($res === false) {
                    throw new Exception('系统繁忙，请稍后重试');
                }
            }
            $data = array_merge($data, $this->getSaveData($this->scenario, $post));

            $data['name'] = strip_tags($data['name']);
            $data['detail'] = strip_tags($data['detail']);

            $addressInfo = (new ConfigAddress)->getAddress($data['province'],$data['city'],$data['area']);
            $data['province_name'] = $addressInfo['province'];
            $data['city_name'] = $addressInfo['city'];
            $data['area_name'] = $addressInfo['area'];

            if (empty($id)) {
                //判断是否有地址，没有的话设置为默认
                $checkFirst['user_id'] = $user['id'];
                $checkFirst['is_delete'] = Status::COMMON_IS_NOT_DELETE;
                $count = static::getCountByWhere($checkFirst);
                if ($count == 0) {
                    $data['is_default'] = Status::COMMON_RADIO_YES;
                }
                $data['create_time'] = date("Y-m-d H:i:s");
                $data['user_id'] = $user['id'];
                $res = static::insertData($data);
            } else {
                $info = static::getOneInfoById($id);
                if (empty($info) || $info['user_id'] != $user['id']) {
                    throw new Exception('未知信息');
                }
                $data['update_time'] = date("Y-m-d H:i:s");
                $res = static::updateData($data, ['id' => $id]);
            }

            if ($res === false) {
                throw new Exception('系统繁忙，请稍后再试');
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '保存成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    /**
     * 获取详细信息
     * @param int $id
     * @return array
     */
    public function getInfo($id = 0)
    {
        try {
            $userInfo = (new User())->checkUser();
            $id = (int) Yii::$app->request->get('id','');
            if (empty($id)) {
                throw new Exception('未知信息');
            }
            $where['id'] = $id;
            $where['user_id'] = $userInfo['id'];

            $info = static::getOneByWhere($where, ['id', 'province','province_name','city_name','area_name', 'city', 'area', "detail", 'name', 'phone', 'is_default']);
            if (!$info) {
                throw new Exception('未知信息');
            }
            $info["is_default"] = $info['is_default'] == Status::COMMON_RADIO_YES;
            return Functions::formatRestAPI(0, '', $info);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 删除地址
     * @param int $id
     * @return array
     */
    public function delInfo($id = 0)
    {
        try{
            $userInfo = (new User())->checkUser();

            $id = (int) $id;
            if (empty($id)) {
                throw new Exception("未知信息");
            }
            $where['id'] = $id;

            $update['is_delete'] = status::COMMON_STATUS_HIDDEN;
            $res = static::updateData($update,$where);
            if (!$res){
                throw new Exception('系统繁忙，请稍后再试');
            }
            return Functions::formatRestAPI(0, '删除成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 获取默认地址
     * @return array
     */
    public function getDefault() {
        try {
            $user = (new User())->checkUser();

            $where['user_id'] = $user['id'];
            $where['is_default'] = Status::COMMON_RADIO_YES;
            $where['is_delete'] = Status::COMMON_STATUS_SHOW;
            $address = static::getOneByWhere($where, ['id', 'province', 'city', 'area', 'province_name','city_name','area_name','name', 'phone', 'is_default','detail']);
            if (empty($address)) {
                $address = static::getOneByWhere(
                    ["user_id" => $user['id'],'is_delete'=>1],
                    ['id', 'province', 'city', 'area', 'province_name','city_name','area_name','name', 'phone', 'is_default','detail']);
            }

            if (!empty($address)) {
                $address["is_default"] = $address['is_default'] == Status::COMMON_RADIO_YES;
            }

            return Functions::formatRestAPI(0, '', $address);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 设置默认地址
     * @return array
     */
    public function saveDefault() {
        $trans = static::getDb()->beginTransaction();

        try {

            $userInfo = (new User())->checkUser();
            $addressId = Yii::$app->request->post('id','');
            if (empty($addressId)) {
                throw new Exception('地址不存在');
            }
            //先将该用户地址全改为非默认    1：默认 ；2：非默认
            $status = static::updateData(['is_default' => Status::COMMON_RADIO_NO],['user_id'=>$userInfo['id']]);
            if($status === false){
                throw new Exception('操作失败');
            }
            $res = static::updateData(['is_default' => Status::COMMON_RADIO_YES], ['id' => $addressId]);
            if($res === false){
                throw new Exception('操作失败');
            }
            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 获取筛选地区
     * @return array
     */
    public function getAddressList($p = 0)
    {
        $where['parentid'] = 1;
        if (!empty($p)) {
            $where['parentid'] = (int) $p;
        }

        $list = ConfigAddress::getCacheByWhere($where, ['id', "areaname as name","parentid as parentId"]);
        $result = null;
        $tmp = [];
        foreach ($list as $k => $v) {
            $tmp[] = [
                'value' => $v['id'],
                'parent' => $v['parentId'],
                'name' => $v['name'],
            ];
        }
        $result = $tmp;
        return Functions::formatRestAPI(0, '', $result);
    }

}
